/*
 * bdbibdRExt.cpp
 *
 *  Created on: Sep 19, 2011
 *      Author: lindenb
 */
#include "throw.h"
#include "bdbibd.h"

#include <R.h>
#include <Rinternals.h>

using namespace std;
using namespace bdb;
extern "C" {


SEXP bdbibd_open(SEXP filename)
	{
	ApplicationReader* handle=NULL;
	if(!isString(filename)) error("db-home is not a string");
	if(length(filename)!=1) error("expected only one filename");

	handle=new (nothrow)  ApplicationReader;
	if(handle==NULL)
		{
		error("Cannot alloc ApplicationReader");
		}
	const char* c_filename=CHAR(STRING_ELT(filename,0));
	handle->env()->open((char*)c_filename,true);
	/** the handle is bound a R variable */
	return R_MakeExternalPtr(handle, R_NilValue, R_NilValue);
	}

SEXP bdbibd_close(SEXP r_handle)
	{
	ApplicationReader* handle = (ApplicationReader*)R_ExternalPtrAddr(r_handle);
	if(handle==NULL) error("handle==NULL");
	handle->env()->close();
	return ScalarInteger(0);
	}

SEXP bdbibd_get(SEXP r_handle,SEXP rsHandle)
	{
	R_len_t i, n = length(rsHandle);
	SEXP ret;
	ApplicationReader* handle = (ApplicationReader*)R_ExternalPtrAddr(r_handle);
	if(handle==NULL) error("handle==NULL");
	if(!isString(rsHandle)) error("rsHandle should be of type character");
	MEM_PROTECT(ret = NEW_LIST((Sint) num_fields));
	for(i=0;i< n;++i)
		{
		s_object *S_fields;

		S_fields=NEW_LIST(2);


		SET_ELEMENT(S_fields, (Sint)0, NEW_STRING());

		VECTOR_ELT(rsHandle, i);
		SET_LST_CHR_EL(output,0,0,C_S_CPY(tmp));
		SET_VECTOR_ELT(ret, i, eval(R_fcall, rho));
		}
	UNPROTECT(1);
	return ret;
	}

}




